package servlets;

import java.io.IOException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import server.ForumAPIService;
import server.controller.WebAdapter;

import database.DBHandler;
import database.DatabaseStub;
import forum.Post;
import forum.Thread;

/**
 * Servlet implementation class ViewThreadsProcessor
 */
// @WebServlet("/ViewThreadsProcessor")
public class ViewThreadsProcessor extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ViewThreadsProcessor() {
		super();
	}

	/**
	 * @see Servlet#init()
	 */
	public void init() throws ServletException {
		super.init();
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		super.destroy();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected synchronized void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("view threads processor. doGet");
		// get session of the request
		HttpSession session = request.getSession();

		Boolean isLoggedIn = (Boolean) session.getAttribute("isLoggedIn");

		if (isLoggedIn == null || !(isLoggedIn.booleanValue())) {
			request.setAttribute("errorMsg", "Please Log In");
			String addr = "http://" + request.getServerName() + ":"
					+ request.getServerPort() + request.getContextPath();

			request.setAttribute("errorLink", addr);
			// get the request dispatcher
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher("/jsp/Error.jsp");

			// forward to the jsp file to display the book list
			dispatcher.forward(request, response);
			return;
		}

		ForumAPIService db = WebAdapter.getInstance();

		// get parameter do of the request
		String action = request.getParameter("do");

		// get the id of the request
		int id = -1;
		if (request.getParameter("id") != null)
			id = Integer.valueOf(request.getParameter("id"));

		if (action.equals("show")) {
			session.setAttribute("threadID", new Integer(id));
			// redirect to the book list servlet
			response.sendRedirect(request.getContextPath() + "/viewPosts");
			return;
		}

		if (action.equals("ajaxShow")) {
			response.setContentType("text/xml");
			response.setHeader("Cache-Control", "no-cache");//browser won't save the results ahead
			// get all posts
			String username = (String) session.getAttribute("username");
			List<Post> allPosts = ((WebAdapter)db).getThread(id, username);
			
			String ans = this.makeReadOnlyPosts(allPosts);
			response.getWriter().write(
					"<div align=\"left\" id=\"thread"+id+"\"> " + ans + " </div>");
			response.getWriter().flush();
			return; 
		}
		String username = (String) session.getAttribute("username");
		
		if (action.equals("check")){
			System.out.println("view threads processor. check");
			int notify = ((WebAdapter) db).getUserNotifies(username);
			response.setContentType("text/xml");
			response.setHeader("Cache-Control", "no-cache");
			String ans = "<response>";
			//check friend notification
			int res = notify & WebAdapter.FRIEND_NOTIFY;
			if (res > 0) {
				ans  += "<friend>y</friend>\n";
			}
			else
				ans  += "<friend>n</friend>\n";
			// check author notification
			res = notify & WebAdapter.AUTHOR_NOTIFY;
			if (res > 0)
				ans += "<author>y</author>\n";
			else
				ans += "<author>n</author>\n";
			ans += "<viewer>n</viewer>\n";
			ans += "</response>";
			System.out.println(ans);
			response.getWriter().write(ans);
			response.getWriter().flush();
			return;
		}
		
		// add thread
		if (action.equals("add")) {

			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher("/jsp/addThread.jsp");

			// forward to the jsp file to display the book list
			dispatcher.forward(request, response);
			return;

		}
		if (action.equals("delete")) {
			// session.setAttribute("username", "username0");
			Boolean isModerator = (Boolean) session.getAttribute("isModerator");
			Integer forumID = (Integer) session.getAttribute("forumID");
			Integer threadID = Integer.parseInt((String) request
					.getParameter("id"));
			String authorOfRemovedPost = request.getParameter("author");
			if (forumID == null || authorOfRemovedPost == null)
				return;

			// if username is author of thread or is moderator
			if (!authorOfRemovedPost.equalsIgnoreCase(username)
					&& (isModerator == null || !isModerator.booleanValue())) {
				request.setAttribute("errorMsg",
						"You do not have a suitable permittions to delete this thread this page");
				String addr = "http://" + request.getServerName() + ":"
						+ request.getServerPort() + request.getContextPath()
						+ "/viewThreads";

				request.setAttribute("errorLink", addr);
				// get the request dispatcher
				RequestDispatcher dispatcher = getServletContext()
						.getRequestDispatcher("/jsp/Error.jsp");

				// forward to the jsp file to display the book list
				dispatcher.forward(request, response);
				return;
			}

			// delete the forum by id
			int res = db.removeThread(threadID.intValue());
			if (res > 0){
				// redirect to the book list servlet
				response.sendRedirect(request.getContextPath() + "/viewThreads");
				return;
			} else{
				
			}

		}
	}

	private synchronized String makeReadOnlyPosts(List<Post> allPosts) {
		String ans = "";
		ans += "<p align=\"center\">\n";
		for (Post p : allPosts) {
			ans += "<br>****************************************<br>\n";
			ans += "<br> No: " + p.getID();
			if (p.getParent() != null)
				ans += "\n <u> Reply to post " + p.getParent().getID()
						+ " </u>";

			ans += "\n<br> <b>" + p.getAuthor() + "</b> posted at <b>" + p.getDate() + "</b>";
			ans += "\n <br> <b> Subject: </b> " + p.getSubject();
			ans += "\n <br> <b> Content: </b> " + p.getContent() + " \n <br> ";
		}
		if (allPosts == null || allPosts.isEmpty())
			ans += "This thread has no posts.\n You may be the first one!";
		ans += "\n</p>";
		return ans;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected synchronized void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// process add forum request
		System.out.println("view threads processor. doPost");
		HttpSession session = request.getSession();
		ForumAPIService db = WebAdapter.getInstance();

		String subject = request.getParameter("subject");
		String content = request.getParameter("content");
		String username = (String) session.getAttribute("username");
		Integer forumID = (Integer) session.getAttribute("forumID");

		Date tmp = GregorianCalendar.getInstance().getTime();
		SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy HH-mm-ss");
		String date = format.format(tmp);
		db.addThread(username, forumID, subject, content, date);

		// redirect to the book list servlet
		response.sendRedirect(request.getContextPath() + "/viewThreads");
	}

}
